package com.example.xyr.myapplication.service;

import android.app.Application;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;

import com.amap.api.maps.model.LatLng;
import com.example.xyr.myapplication.ui.im.ChatUserUtils;
import com.example.xyr.myapplication.utils.LatlonUtils;

public class LatlonService extends Service {
    private Application activity;
    private MyThread myThread;

    public LatlonService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        activity = getApplication();
        myThread = new MyThread();
        myThread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (myThread != null) {
            myThread.stopThread();
            myThread = null;
        }
        super.onDestroy();
    }

    class MyThread extends Thread {
        private boolean isRun = true;

        public MyThread() {

        }

        public void stopThread() {
            isRun = false;
        }

        @Override
        public void run() {
            while (isRun) {
                synchronized (this) {
                    if (isRun) {
                        LatLng latlng = LatlonUtils.getInstance(getApplicationContext()).getLatlng();
                        if (latlng != null) {
                            String strLatlng = latlng.latitude + "&" + latlng.longitude;
                            ChatUserUtils.updateAddRess(strLatlng);
                        } else {
                            SystemClock.sleep(5000);
                            latlng = LatlonUtils.getInstance(getApplicationContext()).getLatlng();
                            if (latlng != null) {
                                String strLatlng = latlng.latitude + "&" + latlng.longitude;
                                ChatUserUtils.updateAddRess(strLatlng);
                            }
                        }
                    }
                }
                SystemClock.sleep(50000);
            }
        }
    }
}
